package com.bw.home.viewmodel

import androidx.lifecycle.viewModelScope
import com.bw.home.intent.DanMuIntent
import com.bw.home.service.CommentService
import com.bw.home.service.DanMuService
import com.bw.home.state.CommentState
import com.bw.home.state.DanMuState
import com.bw.lib_mvi.viewmodel.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

class DanMuViewModel : BaseViewModel<DanMuIntent>() {
    private val service: DanMuService by lazy { DanMuService() }

    //可改变的
    private val _state = MutableStateFlow<DanMuState>(DanMuState.init)

    //可观察的
    val state: StateFlow<DanMuState>
        get() = _state


    override fun handlerIntent() {
        viewModelScope.launch {
            intents.consumeAsFlow().collect {
                when (it) {

                    is DanMuIntent.getDanMu -> {
                        doGetDanMu(it)
                    }

                    is DanMuIntent.sendDanMu -> {
                        doSendDanMu(it)
                    }

                    is DanMuIntent.deleteDanMu -> {
                        doDeleteDanMu(it)
                    }

                    else -> {}
                }
            }
        }
    }

    //删除弹幕
    private fun doDeleteDanMu(it: DanMuIntent.deleteDanMu) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.deleteDanMu(it.id)
            if (data.code == 0) {
                _state.value = DanMuState.deleteDanMu(data.data)
            } else {
                _state.value = DanMuState.Failed
            }
        }
    }

    //发送弹幕
    private fun doSendDanMu(it: DanMuIntent.sendDanMu) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.sendDanMu(it.entity)
            if (data.code == 0) {
                _state.value = DanMuState.sendDanMu(data.data)
            } else {
                _state.value = DanMuState.Failed
            }
        }
    }

    //获取弹幕数据
    private fun doGetDanMu(it: DanMuIntent.getDanMu) {
        viewModelScope.launch(Dispatchers.IO) {
            val data = service.getDanMu(it.type, it.id)
            if (data.code == 0) {
                _state.value = DanMuState.getDanMu(data.data)
            } else {
                _state.value = DanMuState.Failed
            }
        }
    }
}